package com.luom.springbootinit.controller;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.luom.springbootinit.annotation.AuthCheck;
import com.luom.springbootinit.common.BaseResponse;
import com.luom.springbootinit.common.DeleteRequest;
import com.luom.springbootinit.common.ErrorCode;
import com.luom.springbootinit.common.ResultUtils;
import com.luom.springbootinit.constant.UserConstant;
import com.luom.springbootinit.exception.BusinessException;
import com.luom.springbootinit.exception.ThrowUtils;
import com.luom.springbootinit.model.dto.book.BookAddRequest;
import com.luom.springbootinit.model.dto.book.BookUpdateRequest;
import com.luom.springbootinit.model.dto.book.BookQueryRequest;
import com.luom.springbootinit.model.entity.Book;
import com.luom.springbootinit.model.entity.BorrowRecord;
import com.luom.springbootinit.model.entity.User;
import com.luom.springbootinit.model.vo.BookVO;
import com.luom.springbootinit.service.BookService;
import com.luom.springbootinit.service.BorrowRecordService;
import com.luom.springbootinit.service.UserService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.ObjectUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.List;

/**
 * 图书信息接口
 *
 */
@RestController
@RequestMapping("/book")
@Slf4j
public class BookController {

    @Resource
    private BookService bookService;

    @Resource
    private BorrowRecordService borrowRecordService;

    // region 增删改查

    /**
     * 创建图书信息
     *
     * @param bookAddRequest
     * @return
     */
    @PostMapping("/add")
    @AuthCheck(mustRole = UserConstant.ADMIN_ROLE)
    public BaseResponse<Integer> addBook(@RequestBody BookAddRequest bookAddRequest) {
        ThrowUtils.throwIf(bookAddRequest == null, ErrorCode.PARAMS_ERROR);
        Book book = new Book();
        BeanUtils.copyProperties(bookAddRequest, book);
        // 数据校验
        bookService.validBook(book, true);
        // 写入数据库
        boolean result = bookService.save(book);
        ThrowUtils.throwIf(!result, ErrorCode.OPERATION_ERROR);
        // 返回新写入的数据 id
        int newBookId = book.getId();
        return ResultUtils.success(newBookId);
    }

    /**
     * 删除图书信息（仅管理员可用）
     *
     * @param deleteRequest
     * @return
     */
    @PostMapping("/delete")
    @AuthCheck(mustRole = UserConstant.ADMIN_ROLE)
    public BaseResponse<Boolean> deleteBook(@RequestBody DeleteRequest deleteRequest) {
        if (deleteRequest == null || deleteRequest.getId() <= 0) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }int id = deleteRequest.getId();
        // 判断是否存在
        Book oldBook = bookService.getById(id);
        ThrowUtils.throwIf(oldBook == null, ErrorCode.NOT_FOUND_ERROR);
        // 判断是否有人借阅
        List<BorrowRecord> bookIdList = borrowRecordService.query().eq("bookId", oldBook.getId()).list();
        if (ObjectUtils.isNotEmpty(bookIdList)){
            throw new BusinessException(ErrorCode.OPERATION_ERROR,"该图书已被借阅，无法删除");
        }
        // 操作数据库
        boolean result = bookService.removeById(id);
        ThrowUtils.throwIf(!result, ErrorCode.OPERATION_ERROR);
        return ResultUtils.success(true);
    }

    /**
     * 更新图书信息（仅管理员可用）
     *
     * @param bookUpdateRequest
     * @return
     */
    @PostMapping("/update")
    @AuthCheck(mustRole = UserConstant.ADMIN_ROLE)
    public BaseResponse<Boolean> updateBook(@RequestBody BookUpdateRequest bookUpdateRequest) {
        if (bookUpdateRequest == null || bookUpdateRequest.getId() <= 0) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        Book book = new Book();
        BeanUtils.copyProperties(bookUpdateRequest, book);
        // 数据校验
        bookService.validBook(book, false);
        // 判断是否存在
        int id = bookUpdateRequest.getId();
        Book oldBook = bookService.getById(id);
        ThrowUtils.throwIf(oldBook == null, ErrorCode.NOT_FOUND_ERROR);
        // 操作数据库
        boolean result = bookService.updateById(book);
        ThrowUtils.throwIf(!result, ErrorCode.OPERATION_ERROR);
        return ResultUtils.success(true);
    }

    /**
     * 根据 id 获取图书信息（封装类）
     *
     * @param id
     * @return
     */
    @GetMapping("/get/vo")
    public BaseResponse<BookVO> getBookVOById(int id) {
        ThrowUtils.throwIf(id <= 0, ErrorCode.PARAMS_ERROR);
        // 查询数据库
        Book book = bookService.getById(id);
        ThrowUtils.throwIf(book == null, ErrorCode.NOT_FOUND_ERROR);
        // 获取封装类
        return ResultUtils.success(bookService.getBookVO(book));
    }

    /**
     * 分页获取图书信息列表（仅管理员可用）
     *
     * @param bookQueryRequest
     * @return
     */
    @PostMapping("/list/page")
    @AuthCheck(mustRole = UserConstant.ADMIN_ROLE)
    public BaseResponse<Page<Book>> listBookByPage(@RequestBody BookQueryRequest bookQueryRequest) {
        long current = bookQueryRequest.getCurrent();
        long size = bookQueryRequest.getPageSize();
        // 查询数据库
        Page<Book> bookPage = bookService.page(new Page<>(current, size),
                bookService.getQueryWrapper(bookQueryRequest));
        return ResultUtils.success(bookPage);
    }

    /**
     * 分页获取图书信息列表（封装类）
     *
     * @param bookQueryRequest
     * @return
     */
    @PostMapping("/list/page/vo")
    public BaseResponse<Page<BookVO>> listBookVOByPage(@RequestBody BookQueryRequest bookQueryRequest) {
        long current = bookQueryRequest.getCurrent();
        long size = bookQueryRequest.getPageSize();
        // 限制爬虫
        ThrowUtils.throwIf(size > 20, ErrorCode.PARAMS_ERROR);
        // 查询数据库
        Page<Book> bookPage = bookService.page(new Page<>(current, size),
                bookService.getQueryWrapper(bookQueryRequest));
        // 获取封装类
        return ResultUtils.success(bookService.getBookVOPage(bookPage));
    }
    // endregion
}
